#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import os
import sys
import gettext

#To translate
gettext.install("kontrolcu", unicode=1)

LOGOPATH = ":/icons/data/kontrolcu.png"

#To import kontrolcu's library \\ No need to write try: except: here
MODULEPATH = os.getcwd()[:-3] + "src"
sys.path.append(MODULEPATH)
from libkontrolcu import *
import icons_rc

from constants import SUMMARY
from constants import VERSION
VERSION = VERSION[:3] #To get the main release 2.0-alpha-> 2.0

class DnDListWidget(QListWidget): #Drag And Drop QListWidget (New in 2.0)
    def __init__(self, parent=None):
        super(DnDListWidget, self).__init__(parent)
        self.setAcceptDrops(True)
        self.setDragEnabled(True)
        if os.name == "nt":
            self.cstatus = False #Because of a fatal error on nt!
        else:
            self.cstatus = True #Means its ready to do drag and drop
    def getSize(self):
        files = self.getListItems()
        mysize = 0
        for i in files:
            mysize += os.stat(i).st_size 
        return mysize
    def getListItems(self):
        value = True
        rnumber=0
        files = []
        while value:
            try:
                files.append(self.item(rnumber).text())
                rnumber +=1
            except AttributeError:
                value = False
        return files
    def dragEnterEvent(self, event):
        if self.cstatus:
            event.accept()
    def dragMoveEvent(self, event):
        if self.cstatus:
            event.setDropAction(Qt.MoveAction)
            event.accept()
    def dropEvent(self, event):
        if self.cstatus:
            print makeBlue( "-> " + event.mimeData().text())
            if event.mimeData().text():
                mimetext = event.mimeData().text()
                if "\n" in mimetext:
                    mimetext = mimetext.split("\n")
                    for i in mimetext:
                        i = i[7:]
                        if i == " ":
                            continue
                        if "/r" in i:
                            i = i[:-1]
                        if os.path.isdir(i):
                            iAddress = i + os.sep
                            for j in os.listdir(i):
                                if os.path.isfile(iAddress + j):
                                    self.addItem(iAddress + j)
                        elif os.path.isfile(i):
                            self.addItem(i)
                else:
                    text = event.mimeData().text()[7:]
                    if os.path.isdir(text):
                        textAddress = text + os.sep
                        for i in os.listdir(text):
                            if os.path.isfile(textAddress + i):
                                print makeBlue( " |->" + textAddress + i )
                                self.addItem(textAddress + i)
                    elif os.path.isfile(text):
                        self.addItem(text)
                event.accept()
            else:
                event.ignore()



#Planing for 2.1 - experimental
class DnDTableWidget(QTableWidget):
    def __init__(self, parent=None):
        super(DnDTableWidget, self).__init__(parent)
        self.setColumnCount(2)
        self.setRowCount(20)
        self.setHorizontalHeaderLabels([_("File Name:"), _("Check Summary:")])
        self.setAlternatingRowColors(True)
        #self.setSelectionBehavior(QTableWidget.SelectRows)
        self.setSelectionMode(QTableWidget.SingleSelection)
        item = QTableWidgetItem("main.py")
        checkitem = QTableWidgetItem("123ASF2516812344SDAG512")
        #setting item(row, column, item)
        self.setItem(0, 0,item)
        self.setItem(0, 1, checkitem)
        setEditTriggers(QAbstractItemView.NoEditTriggers)
#TabWidgets: Best way to make tabs is creating classes :)
class CheckWidget(QWidget):
    def __init__(self, parent=None):
        super(CheckWidget, self).__init__(parent)

        # Main Layout for Check Tab
        mainlayout = QHBoxLayout()
        
        
        #Left Side <---
        leftvertical = QVBoxLayout()
        self.checktypes = ["md5","sha1","sha224","sha256","sha384","sha512"]
        self.ltypes = QLabel(_("Check Types:"))
        self.typecombox = QComboBox()
        self.typecombox.addItems(self.checktypes)
        
        leftvertical.addWidget(self.ltypes)
        leftvertical.addWidget(self.typecombox)

        #Big blank here

        leftvertical.addStretch(6)
        self.logo = QPixmap(LOGOPATH)
        self.logolabel = QLabel()
        self.logolabel.setPixmap(self.logo)
        
        self.addFile = QPushButton(_("Add File(s)")) 
        self.checkit = QPushButton(_("Check Now!"))
        leftvertical.addWidget(self.logolabel)
        leftvertical.addWidget(self.addFile)
        leftvertical.addWidget(self.checkit)

        #Right Side --->
        rightvertical = QVBoxLayout()
        righthv = QHBoxLayout()
        self.saveToClip = QPushButton(_("Copy To Clipboard"))
        self.saveToFile = QPushButton(_("Save To File"))
        self.deleteSelected = QPushButton(_("Delete Selected"))

        righthv.addWidget(self.saveToClip)
        righthv.addWidget(self.saveToFile)
        righthv.addWidget(self.deleteSelected)
        
        self.mainlist = DnDListWidget()
        #self.mainlist = DnDTableWidget()

        rightvertical.addLayout(righthv)
        rightvertical.addWidget(self.mainlist)
        
        #Main Side -|-

        mainlayout.addLayout(leftvertical)

        mainlayout.addLayout(rightvertical)
        self.setLayout(mainlayout)
        
        
# For the File Tab
class FileWidget(QWidget):
    def __init__(self, parent=None):
        super(FileWidget, self).__init__(parent)
        filelayout = QVBoxLayout()
        firstline = QHBoxLayout()
        secondline = QHBoxLayout()
        
        #first line items
        self.selectedConLabel = QLabel(_("Selected Control File:"))
        self.selectedConLine = QLineEdit()
        self.selectedConBut = QPushButton("...")
        
        firstline.addWidget(self.selectedConLabel)
        firstline.addWidget(self.selectedConLine)
        firstline.addWidget(self.selectedConBut)

        #secon line items
        self.selectedDirLabel = QLabel("    " + _("Selected Directory:"))
        self.selectedDirLine = QLineEdit()
        self.selectedDirBut = QPushButton("...")

        self.filebrowser = QTextBrowser()

        secondline.addWidget(self.selectedDirLabel)
        secondline.addWidget(self.selectedDirLine)
        secondline.addWidget(self.selectedDirBut)
        self.analyzeIt = QPushButton(_("Analyze It"))

        filelayout.addLayout(firstline)
        filelayout.addLayout(secondline)
        filelayout.addWidget(self.filebrowser)
        filelayout.addWidget(self.analyzeIt)
        self.setLayout(filelayout)

# For the Compare Tab
class CompWidget(QWidget):
    def __init__(self, parent=None):
        super(CompWidget, self).__init__(parent)
        complayout = QVBoxLayout()
        firstline = QHBoxLayout()
        secondline = QHBoxLayout()
        
        #first line items
        self.selectedFileLabel = QLabel(_("Selected File:"))
        self.selectedFileLine = QLineEdit()
        self.selectedFileBut = QPushButton("...")
        
        firstline.addWidget(self.selectedFileLabel)
        firstline.addWidget(self.selectedFileLine)
        firstline.addWidget(self.selectedFileBut)

        #secon line items
        self.selectedSumLabel = QLabel("    "+_("Checksum:"))
        self.selectedSumLine = QLineEdit()
        self.selectedSumBut = QPushButton( _("Paste"))


        secondline.addWidget(self.selectedSumLabel)
        secondline.addWidget(self.selectedSumLine)
        secondline.addWidget(self.selectedSumBut)

        self.checksumlabel = QLabel(_("Your checksum:"))

        self.compareIt = QPushButton(_("Compare"))
        self.combrowser= QTextBrowser()
  
        complayout.addLayout(secondline)
        complayout.addWidget(self.checksumlabel)
        complayout.addLayout(firstline)
        complayout.addWidget(self.combrowser)
        complayout.addWidget(self.compareIt)
        self.setLayout(complayout)


#class StatusBar(QStatusBar):
#    def __init__(self, parent=None):
#        super(StatusBar, self).__init__(parent)


class MainKontrolcu(QDialog):
    def __init__(self, parent=None):
        super(MainKontrolcu, self).__init__(parent)
        tabwidget = QTabWidget()
        mainlayout = QVBoxLayout()
        self.tabconlayout = CheckWidget()
        self.tabfilelayout = FileWidget()
        self.tabcomplayout = CompWidget()

        #About buttons
        aboutlayout = QHBoxLayout()
        self.aboutthis = QPushButton(_("About Kontrolcu"))
        self.aboutqt = QPushButton(_("About Qt"))
        self.helpme = QPushButton("(?)")
        self.fontsizer = QSlider(Qt.Horizontal)
        self.fontsizer.setRange(4,30)
        self.fontsizer.setValue(10)
        
        aboutlayout.addWidget(self.fontsizer)
        aboutlayout.addStretch(3)
        aboutlayout.addWidget(self.aboutqt)
        aboutlayout.addWidget(self.aboutthis)
        aboutlayout.addWidget(self.helpme)

        #self.statusbar = QStatusBar()
        #self.statusbar.showMessage(_("Kontrolcu is ready for duty!"), 10000)
        tabwidget.addTab(self.tabconlayout, _("Check"))
        tabwidget.addTab(self.tabfilelayout, _("Check From File"))
        tabwidget.addTab(self.tabcomplayout, _("Compare With Checksum"))

        self.welcome = QLabel("<font color=black size=30><b>%s</b></font>" % ("Kontrolcu" + " " + VERSION))
        self.welcometext = QLabel(_(SUMMARY))

        
        mainlayout.addWidget(self.welcome)
        mainlayout.addWidget(self.welcometext)
        mainlayout.addWidget(tabwidget)
        mainlayout.addLayout(aboutlayout)
        #mainlayout.addWidget(self.statusbar)

        self.setLayout(mainlayout)
        self.setWindowTitle("Kontrolcu")
        self.icon = QIcon(LOGOPATH)
        self.setWindowIcon(self.icon)
        
